/*
 * C Implementation: grib_copy_message
 *
 * Description: How to copy a GRIB message in memory (拷贝一个 message)
 *
 */
#include <stdio.h>
#include <assert.h>
#include "eccodes.h"

static void usage(const char* prog)
{
    fprintf(stderr, "Usage is: %s input_file ouput_file\n", prog);
}

int sfx_grib_copy_message()
{
    int err = 0;

    FILE* in                    = NULL;
    codes_handle* source_handle = NULL;

    char* infile = "D:\\temp\\era5-levels-members.grib";
    char* oufile = "d:\\temp\\out.grib";

    in = fopen(infile, "rb");
    if (!in) {
        perror("ERROR: unable to input file");
        return 1;
    }

    // loop over the GRIB messages in the source
    while ((source_handle = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err)) != NULL) {
        //
        size_t totalLength = 0, size = 0;
        const void* buffer       = NULL;
        codes_handle* new_handle = NULL;

        CODES_CHECK(codes_get_message_size(source_handle, &totalLength), 0);

        CODES_CHECK(codes_get_message(source_handle, &buffer, &size), 0);
        assert(size == totalLength);

        new_handle = codes_handle_new_from_message(0, buffer, totalLength);

        if (new_handle == NULL) {
            perror("ERROR: could not create GRIB handle from message");
            return 1;
        }

        CODES_CHECK(codes_set_long(new_handle, "hour", 18), 0);
        CODES_CHECK(codes_write_message(new_handle, oufile, "w"), 0);

        codes_handle_delete(new_handle);
        codes_handle_delete(source_handle);

        break;
    }

    fclose(in);

    return 0;
}
